package top.codedance.iotp.registy.distributed;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.ServerMeta;
import top.codedance.iotp.common.util.HttpRequestUtil;
import top.codedance.iotp.registy.RegistryApplication;
import org.apache.log4j.Logger;

import java.util.Map;
import java.util.Set;

public class RegistyServer {
    private static Logger logger = RegistryApplication.getLogger(RegistyServer.class);

    public RegistyServer() {}

    public void run() {
        try {
            RegistryApplication.syslogInfo("Registy server success");
            while (true) {
                if(RegistryApplication.isMaster) {
                    RegistryApplication.workerPool.submit(() -> {
                        JSONObject post;
                        ServerMeta sm;
                        Set<Map.Entry<String, ServerMeta>> entries = RegistryApplication.servers.entrySet();
                        for (Map.Entry<String, ServerMeta> item : entries) {
                            try {
                                sm = item.getValue();
                                if (sm != null) {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("username", sm.getNetUsername());
                                    jsonObject.put("password", sm.getNetPassword());
                                    logger.debug("检测服务端");
                                    post = HttpRequestUtil.post(sm.getHttpBindHost() + "/rest/api/server/information", jsonObject.toJSONString());
                                    if (post.getIntValue("status") != 200) {
                                        RegistryApplication.delServer(item.getKey());
                                        RegistryApplication.delClientForServer(item.getKey());
                                        logger.debug("移除没响应服务端：" + item.getKey());
                                    }
                                }
                            } catch (Exception e) {
                                logger.debug(e.getMessage());
                            }
                        }
                    });
                }

                try {
                    Thread.sleep(2000);
                } catch (Exception ex) {
                }
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
        } finally {
            try {
                Thread.sleep(1000);
            } catch (Exception ex) {
            }
            run();
        }
    }
}
